#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import os

from app import db
from app.test import bl
from .model import Article
from flask import render_template, request, views, jsonify, url_for
from werkzeug.utils import secure_filename
from app.config import UP_FOLDER
from PIL import Image

ALLOWED_FILE = set(['png', 'jpg', 'jepg', 'gif'])


@bl.route('/', methods=['GET', 'POST'])
def index():
    if request.method == "GET":
        return render_template('index.html')
    elif request.method == "POST":
        print(request.form)
        content = request.form.get('content_html')
        article = Article(body=content)
        db.session.add(article)
        db.session.commit()
        return '12312321'


@bl.route('/show')
def show():
    article = db.session.query(Article).filter(Article.id == 2).first()
    print(article.body)
    return render_template('show.html', **{'article': article})


@bl.route('/test')
def test():
    return render_template('test.html')


def allow_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_FILE


class Uploadfile(views.MethodView):
    def post(self):
        msg = {'success': 0, 'message': '上传失败', 'url': None}
        file = request.files['editormd-image-file']
        if file and allow_file(file.filename):
            filename = "{0}.{1}".format(request.args.get('guid'), file.filename.rsplit('.', 1)[1])
            # 将文件切割成 320*180的大小
            img = Image.open(file)  # 打开文件对象
            outfile = img.resize([320, 180], Image.ANTIALIAS)  # 重定义大小
            outfile.save(os.path.join(UP_FOLDER, filename))  # 保存文件
            # 这里是保存原文件
            # file.save(os.path.join(UP_FOLDER, filename))
            msg['success'] = 1
            msg['message'] = '上传成功'
            msg['url'] = url_for('static', filename='uploadfile/{}'.format(filename))
        print(request.args.get('guid'))
        return jsonify(msg)


bl.add_url_rule('/uploadfile/', endpoint='uploadfile', view_func=Uploadfile.as_view('uploadfile'))
